package cn.sccl.dirms.monitor.controller;

import cn.sccl.common.zabbix.Zabbix;
import freemarker.ext.beans.HashAdapter;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 监控主机
 * Created by liupan on 2017/3/6.
 */
@RestController
@RequestMapping(value = "/dirms/monitor/history")
public class HistoryController {


    /**
     * 获取某一个组的主机数据
     *
     * @param itemid 主机id
     */
    @RequestMapping(value = "/get/{itemid}", method = {RequestMethod.POST, RequestMethod.GET})
    public List<Map<String, Object>> getHistoryByItemId(@PathVariable String itemid) {
        Zabbix zabbix = Zabbix.getZabbix();

        //获取监控项的值类型
        String  valueType;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("itemids", itemid);
        String[] filter = new String[]{"value_type","itemid"};
        params.put("filter", filter);
        Map<String, Object> itemRes = zabbix.call("item.get", params);
        List<Map<String, Object>> itemList = (List<Map<String, Object>>) itemRes.get("result");
        if(itemList != null && itemList.size() == 1){
            valueType = (String)itemList.get(0).get("value_type");
        }else{
            return null;
        }
        if(valueType == null || valueType.equals("")){
            valueType =  "3";
        }
        params.clear();
        params.put("output", "extend");
        params.put("itemids", itemid);
        params.put("history", valueType);
        Map<String, Object> result = zabbix.call("history.get", params);
        List<Map<String, Object>> mapList = (List<Map<String, Object>>) result.get("result");
        updateClock(mapList);
        return mapList;
    }

    /**
     * 获取某一个组的主机数据
     *
     * @param itemid 主机id
     */
    @RequestMapping(value = "/getbytime/{itemid}/{timefrom}/{timetill}", method = {RequestMethod.POST, RequestMethod.GET})
    public Object getHistoryByItemIdTime(@PathVariable String itemid, @PathVariable String timefrom, @PathVariable String timetill, @RequestParam Integer size,@RequestParam Integer page,@RequestParam Integer pageSize) {
        Zabbix zabbix = Zabbix.getZabbix();
        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, Object> result;
        List<Map<String, Object>> mapList;
        //获取监控项的值类型
        String  valueType;
        params.put("itemids", itemid);
        String[] filter = new String[]{"value_type","itemid"};
        params.put("filter", filter);
        Map<String, Object> itemRes = zabbix.call("item.get", params);
        List<Map<String, Object>> itemList = (List<Map<String, Object>>) itemRes.get("result");
        if(itemList != null && itemList.size() == 1){
            valueType = (String)itemList.get(0).get("value_type");
        }else{
            return null;
        }
        if(valueType == null || valueType.equals("")){
            valueType =  "3";
        }
        params.clear();
        params.put("output", "extend");
        params.put("itemids", itemid);
        params.put("sortfield", "clock");
        params.put("sortorder", "DESC");
        params.put("history",valueType);
        if(size != null && size > 0) {
            params.put("limit", size);
        }else{
            params.put("time_from", timefrom);
            params.put("time_till", timetill);
        }

        result = zabbix.call("history.get", params);
        mapList = (List<Map<String, Object>>) result.get("result");
        updateClock(mapList);
        if(page == null || page < 0){
            page = 1;
        }
        if(pageSize == null || pageSize < 0){
            pageSize = 20;
        }
        Map<String,Object> pageRes = new HashMap<>();
        pageRes.put("total",mapList.size());

        List<Map<String, Object>> res = new ArrayList<>();
        for(int i=(page-1)*pageSize;i<page*pageSize;i++){
            try {
                Map m = mapList.get(i);
                m.put("index",i+1);
                res.add(m);
            }catch (Exception e){
                break;
            }
        }
        pageRes.put("page",page);
        pageRes.put("pageSize",pageSize);
        pageRes.put("rows",res);
        return pageRes;
    }
    /**
     * 获取某一个组的主机数据
     *
     * @param itemid 主机id
     */
    @RequestMapping(value = "/get/{itemid}/{timefrom}/{timefill}", method = {RequestMethod.POST, RequestMethod.GET})
    public List<Map<String, Object>> getRangeHistoryByItemId(@PathVariable String itemid, @PathVariable String timefrom, @PathVariable String timefill) {
        Zabbix zabbix = Zabbix.getZabbix();
        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, Object> result;
        List<Map<String, Object>> mapList;
        //获取监控项的值类型
        String  valueType;
        params.put("itemids", itemid);
        String[] filter = new String[]{"value_type","itemid"};
        params.put("filter", filter);
        Map<String, Object> itemRes = zabbix.call("item.get", params);
        List<Map<String, Object>> itemList = (List<Map<String, Object>>) itemRes.get("result");
        if(itemList != null && itemList.size() == 1){
            valueType = (String)itemList.get(0).get("value_type");
        }else{
            return null;
        }
        if(valueType == null || valueType.equals("")){
            valueType =  "3";
        }
        params.clear();
        params.put("output", "extend");
        params.put("itemids", itemid);
        params.put("time_from", timefrom);
        params.put("time_till", timefill);
        params.put("history",valueType);
        //前1天时间点的时间戳
        long daybeginTime = (System.currentTimeMillis() / 1000) - 86400;
        //如果是浮点型或整型  且时间不是当前1天之内的其他范围获取趋势数据
        if( ("0".equals(valueType) || "3".equals(valueType) ) && Long.valueOf(timefrom) < daybeginTime){
            params.remove("history");
            result = zabbix.call("trend.get", params);
            List<Map<String, Object>> trendList = (List<Map<String, Object>>) result.get("result");
            mapList = this.trend2History(trendList);
        }else{//其他类型的数据 直接取历史数据
            result = zabbix.call("history.get", params);
            mapList = (List<Map<String, Object>>) result.get("result");
        }
        updateClock(mapList);
        return mapList;
    }

    private static void updateClock(List<Map<String, Object>> mapList) {
        if(mapList != null && !mapList.isEmpty()) {
            Calendar cal = Calendar.getInstance();
            for (Map<String, Object> map : mapList) {
                long ns = MapUtils.getLongValue(map, "ns", 0) / 1000000;
                cal.setTimeInMillis(MapUtils.getLongValue(map, "clock", 0) * 1000 + ns);
                map.put("clock", DateFormatUtils.format(cal.getTime(), "yyyy-MM-dd HH:mm:ss"));
            }
        }
    }

    private List<Map<String, Object>> trend2History(List<Map<String, Object>> trendList) {
        List<Map<String, Object>> tmpList = new ArrayList<>();
        Map<String, Object> tmp;
        for (Map<String, Object> m : trendList) {
            tmp = new HashMap<>();
            tmp.put("clock",m.get("clock"));
            tmp.put("value", m.get("value_avg"));
            tmpList.add(tmp);
        }
        return tmpList;
    }
}
